package com.cwx.web;

import com.cwx.pojo.Blog;
import com.cwx.service.BlogService;
import com.cwx.service.TagsService;
import com.cwx.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagsService tagsService;

    @Autowired
    private BlogService blogService;

    //跳转到关于我页面
    @GetMapping("/about")
    public String toAbout(){
        return "about";
    }


    //博客首页
    @GetMapping("/")
    public String index(Model model,
                        @PageableDefault(size = 6,sort = "updateTime", direction = Sort.Direction.DESC) Pageable pageable){
//        throw new five00Exception("代码错误");  //抛出异常就会自动跳转到500页面
        //边上的分类  按照分类对应的博客数量来查找到
        model.addAttribute("types",typeService.listTypeTop(6));
        //边上的标签  按照标签对应的博客数量来查找的
        model.addAttribute("tags",tagsService.listTagTop(10));
        //首页的博客  按照推荐更新时间来查找的
        model.addAttribute("page",blogService.listBlog(pageable));
        //边上的推荐博客  按照更新时间来查找博客
        model.addAttribute("recommendBlog",blogService.listBlogTop(6));
        return "index";
    }

    //跳转到首页
    @GetMapping("/index")
    public String toIndex(){
        return "redirect:/";
    }

    //全局搜索页面
    @PostMapping("/search")
    public String search(Model model,
                         @PageableDefault(size = 6,sort = "updateTime", direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query){
        Page<Blog> blogs = blogService.ListBlogSearch("%" + query + "%", pageable);
        model.addAttribute("page",blogs);
        model.addAttribute("query",query);

        return "search";
    }

    //点击博客标题和首图  跳转到博客内容页面
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
        Blog blog = blogService.getAndConvert(id);
        model.addAttribute("blog",blog);
        model.addAttribute("newBlogs",blogService.listBlogTop(3));
        return "Blog";
    }


    //底部的推荐博客推荐
    @GetMapping("/footer/newblog")
    public String newBlogs(Model model){
        model.addAttribute("newBlogs",blogService.listBlogTop(3));
        return "_fragment :: newBlogList";
    }

}
